<template>
  <div class="body">
    <div class="editAlert" v-if="alertState">
      <div class="Pop_title">
        {{ alertTitle }}
      </div>
      <el-form label-width="130px" :model="editForm" ref="formRef" class="editForm" :rules="editFormRoules">
        <el-form-item label="分类名称" prop="title">
          <el-input v-model.trim="editForm.title" placeholder="请输入分类名称" class="search_input" />
        </el-form-item>
      </el-form>
      <div class="footer_btn">
        <el-button type="primary" @click="affirm(formRef)">确认</el-button>
        <el-button class="rigthBtn" @click="cancel">取消</el-button>
      </div>
    </div>
    <div class="content" v-if="!alertState">
      <div class="search_box">
        <el-form label-width="auto" :model="search" class="search_form">
          <el-form-item label="分类标题" label-position="top">
            <el-input v-model="search.title" placeholder="请输入标题" class="search_input input_height"
              @input="searchData" />
          </el-form-item>
          <el-form-item label="创建时间" label-position="top">
            <el-date-picker type="daterange" v-model="search.time" size="default" start-placeholder="开始时间"
              end-placeholder="结束时间" format="YYYY/MM/DD" value-format="YYYY-MM-DD" unlink-panels
              @change="searchData"></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div class="line"></div>
      <div class="operateBtn">
        <el-button type="primary" class="button_height" @click="addAlter">添加</el-button>
        <el-button type="danger" class="button_height" @click="delePop(selectedIds)">批量删除</el-button>
      </div>
      <el-table :data="pageCount" class="label" @selection-change="checkall">
        <el-table-column type="selection" />
        <el-table-column prop="id" label="id" align="center" />
        <el-table-column prop="title" label="名称" align="center" />
        <el-table-column prop="createtime" label="创建时间" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <div class="operate_box">
              <p class="edit" @click="editAlter(scope.row)">编辑</p>
              <p class="delete" @click="delePop([scope.row.id])">删除</p>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="custom_container">
        <el-pagination @size-change="pageNum" @current-change="pageChange" :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]" :page-size="pageSize" layout="sizes, prev, pager, next, jumper"
          :total="pageData.length" class="custom_pagination" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { food_shoptypeList, food_shoptypeAdd, food_shoptypeDel } from '/@/api/food/food_shoptype/index';
import { ElMessage, FormInstance, FormRules, UploadFile } from 'element-plus';
import { ElMessageBox } from 'element-plus';


interface FoodType {
  id: number;
  title: string;
  createtime: string;
}

const data = ref<FoodType[]>([]);
const pageData = ref<FoodType[]>([]);
// 分页页数
const currentPage = ref(1);
// 一页的数据
const pageSize = ref(10);
const editId = ref(0);
const search = reactive({
  title: '',
  time: '',
})
const formRef = ref<FormInstance>();

const editForm = reactive({
  id: '',
  title: '',
})

const repeat = (rule: any, value: any, callback: any) => {
  // 检查是否有重复标题（排除当前编辑的条目）
  const isDuplicate = data.value.some(item =>
    item.title === value &&
    item.id !== editId.value // 如果是编辑模式，跳过当前条目
  );
  if (isDuplicate) {
    callback(new Error('不能添加重复的店铺'));
  } else {
    callback(); // 验证通过
  }
}

const editFormRoules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
    { validator: repeat, trigger: 'blur' }
  ],
})
// 弹窗状态
const alertState = ref(false);
// 弹窗title
const alertTitle = ref('');

const getData = () => {
  food_shoptypeList().then((res: any) => {
    console.log(res)
    data.value = res.data;
    pageData.value = res.data;
  })
}
getData();

// 计算当前页码的起始索引和结束索引，并返回对应区间的数据
const pageCount = computed(() => {
  // 计算起始索引，基于当前页码和每页大小
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return pageData.value.slice(start, end);
});
/* 分页改变 */
const pageChange = (val: number) => {
  currentPage.value = val;
};
/* 分页大小改变 */
const pageNum = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 获取全选的id
const selectedIds = ref<any[]>([]);
const checkall = (val: any) => {
  selectedIds.value = val.map((item: any) => item.id).filter((id: number) => id);
};

// 添加弹窗
const addAlter = () => {
  alertTitle.value = '添加';
  alertState.value = true;
  editForm.id = '';
}

// 编辑弹窗
const editAlter = (item: any) => {
  alertTitle.value = '编辑';
  editId.value = item.id;
  alertState.value = true;
  editForm.title = item.title;
  editForm.id = item.id;
}
// 添加确认接口
const affirm = async (formEl: FormInstance | undefined) => {
  await formEl?.validate((valid, fields) => {
    if (valid) {
      food_shoptypeAdd({ id: editForm.id, title: editForm.title }).then((res) => {
        console.log(res);
        ElMessage({
          message: res.msg,
          type: 'success',
        })
        alertState.value = false;
        getData();
      });
    }
  });
}
// 关闭弹窗函数
const cancel = () => {
  alertState.value = false;
  editForm.title = '';
  editForm.id = '';
};

const delePop = (id: any) => {
  if (id.length <= 0) {
    ElMessage.error('请选择要删除的数据')
    return;
  }
  ElMessageBox.confirm("确定要删除这些数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    food_shoptypeDel({ ids: id.join() }).then((res) => {
      if (res.code == 1) {
        ElMessage.success(res.msg);
        getData();
      }
    }).catch((error: any) => {
      console.log(error);
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
}

// 搜索函数
const searchData = () => {
  pageData.value = data.value;
  const filteredData = () => {
    // 无搜索词时返回全部数据
    if (search.title == '' && search.time.length == 0) {
      return (pageData.value = data.value);
    }
    return pageData.value.filter((item) => {
      console.log(item.createtime);

      // 检查每个字段是否满足相应条件（如果该搜索条件存在）
      const nameMatch =
        !search.title || (item.title && item.title.toLowerCase().includes(search.title.toLowerCase()));
      const timeMatch =
        search.time.length == 0 ||
        (item.createtime >= search.time[0] && item.createtime <= search.time[1]);
      return nameMatch && timeMatch;
    });
  };
  pageData.value = filteredData();
};


</script>

<style scoped>
.content {
  padding: 50px;
  margin: 2%;
  position: relative;
  background-color: white;
}

.line {
  width: 100%;
  height: 1px;
  margin: 25px 0;
  background-color: #e8e7e7;
}

.search_form {
  width: 100%;
  display: flex;
  margin-bottom: -22px;
}

.search_input {
  width: 240px;
  margin-right: 30px;
}

.input_height {
  height: 33px;
}

.button_height {
  height: 30px;
}

.operateBtn {
  display: flex;
  margin-top: 10px;
}

.label {
  margin-top: 10px;
}

.operate_box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit {
  color: #409EFF;
  cursor: pointer;
  margin: 0px 10px;
}

.delete {
  color: #F56C6C;
  cursor: pointer;
  margin: 0px 10px;
}

.custom_container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}

.editAlert {
  position: absolute;
  width: 100%;
  overflow: auto;
  background-color: white;
  top: 0;
  right: 0;
  z-index: 30;
}

.Pop_title {
  padding: 2%;
  border-bottom: 1px solid #ddd;
}

.editForm {
  padding: 2%;
}

.footer_btn {
  display: flex;
  justify-content: end;
  margin-top: 30%;
  margin-right: 5%;
  margin-bottom: 2%;
}

.rigthBtn {
  margin-left: 5%;
}
</style>